package cn.trkj.server.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author admin
 * @date 2020/2/29 10:40 下午
 */

public class DBUtil {


    private static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
    public static Connection conn = null;

    //静态代码块最先执行，先执行一次
    static {
        try {
            //加载驱动
            Class.forName(DRIVER_CLASS_NAME);
        } catch (Exception e) {
            System.out.println("数据库连接失败");
        }
    }

    /**
     * 单例模式，使对象唯一性
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            Class clazz = Class.forName("com.mysql.jdbc.Driver");
            clazz.newInstance();
//            final String DB_URL = "jdbc:mysql://127.0.0.1:3306/xn_file";
//            final String USER = "root";
//            final String PASS = "root";
            final String DB_URL = "jdbc:mysql://172.16.40.200:3306/xn_file?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&&useSSL=true&verifyServerCertificate=false&requireSSL=true&&enabledTLSProtocols=TLSv1";
            final String USER = "xianning";
            final String PASS = "azAZ123@XN";
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            conn.setAutoCommit(true);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return conn;
    }


    public static ResultSet executeQuery(Connection connection, String sql,
                                         Object... params) throws Exception {
        ResultSet rs = null;
        if (connection != null) {
            PreparedStatement ps = connection.prepareStatement(sql);
            if (params != null && params.length > 0) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs = ps.executeQuery();
        }
        return rs;
    }

    public static void close(ResultSet rs, Connection connection) throws
            Exception {
        try {
            if (rs != null) {
                rs.close();
            }
        } finally {
            if (connection != null) {
                connection.close();
            }
        }
    }


//    public static int executeUpdate(Connection connection, String
//            sql, Object... params) throws Exception {
//        int res = 0;
//        if (connection != null) {
//            PreparedStatement ps = connection.prepareStatement(sql);
//            if (params != null && params.length > 0) {
//                for (int i = 0; i < params.length; i++) {
//                    ps.setObject(i + 1, params[i]);
//                }
//            }
//            res = ps.executeUpdate();
//        }
//        return res;
//    }


}
